<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;

class Category extends Model
{
    use ModelTree, AdminBuilder;

    protected $fillable = [
        'name',
        'summary',
        'parent_id',
        'sort',
    ];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setOrderColumn('sort');
        $this->setTitleColumn('name');
    }

    public function scopeOptions(Builder $q)
    {
        return $q->doesntHave('children')->get()->pluck('name', 'id');
    }

    public function scopeAllCategory(Builder $query)
    {
        return $query->with('cover')->whereIn('parent_id', [0, 1]);
    }

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    public function cover()
    {
        return $this->hasOne(Image::class, 'type_id')
            ->where('type', Image::CATEGORY_COVER);
    }

    public function coupons()
    {
        return $this->belongsToMany(Coupon::class, 'category_coupons')->canUse();
    }
}
